import {app, BrowserWindow, ipcMain, nativeImage} from 'electron'
import {createWindow, setMainWindowOptions} from "./module/createWindow.ts";
import {initializeDOMListeners} from "./module/domEvent.ts";
import {mainWindow, otherWindow} from "./module/options.ts";
import path from "node:path";
import * as url from "url";


// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x1
const MODE = import.meta.env.MODE
process.env.DEV_BASE_URL = import.meta.env.VITE_DEV_URL
process.env.DIST = path.join(__dirname, '../dist')


console.log(process.env.DEV_BASE_URL)
app.on('activate', () => {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) {
        const win = createWindow({
            ...mainWindow,
            icon: nativeImage.createFromPath(path.join(process.env.DIST, './pika.ico'))
        })
        setMainWindowOptions(win)
    }
})

app.whenReady().then(() => {
    const win = createWindow({
        ...mainWindow,
        icon: nativeImage.createFromPath(path.join(process.env.DIST, './icon/pika.ico'))
    })
    setMainWindowOptions(win)
    initializeDOMListeners(win)

    ipcMain.on('open-other-window', () => {
        const win2 = createWindow(otherWindow)
        if (MODE === 'development') {
            win2.loadURL(process.env.DEV_BASE_URL + 'other').then(() => {
                initializeDOMListeners(win2, {isOther: true})
            })
        } else {
            // win.loadFile('dist/index.html')
            const indexPath = path.join(process.env.DIST, './index.html')
            let filePath = url.format({
                protocol: 'file:',
                pathname: indexPath,
                slashes: true
            })
            filePath += '#/other'
            win2.loadURL(filePath).then(() => {
                initializeDOMListeners(win2, {isOther: true})
            })
        }
    })
    // 获取当前聚焦的窗口
    ipcMain.handle('get-focus', () => {
        const currentWindow = BrowserWindow.getFocusedWindow()
        if (currentWindow) return currentWindow.id
        return null
    })
})
